var TableListData;
var itemPerPage = 10;
var limitFrom = 0;
$(document).ready(function(){
	loadTable();
	setSelectToCombobox();
	setRadioToSets();
	setSliderSearch();
	$("#tabs").tabs();
	$("#tabs_view").tabs();
	$("#btn_add").click($.fn.GO_UPDATE);
	$("#btn_dialog_search").click($.fn.DIALOG_SEARCH);
	$( "#dialog-message" ).dialog({
		modal: true,
		autoOpen: false,
		buttons: {
			'ok': function() {
				$( this ).dialog( "close" );
			}
		}
	});
});

$.fn.DIALOG_SEARCH = function (){
	$("#dialog-search").dialog({
		modal: true,
		width: 550,
		height:400,
		buttons: {
			'submit': function() {
//				$('#search_frm').submit();
				loadTable();
				var $slider = $("#bed-capacity-range");
				$slider.slider("values", 0, 0);
				$slider.slider("values", 1, 0);
				$('#search_frm')[0].reset();
				$( this ).dialog( "close" );
			},
			'cancel': function(e) {
				var $slider = $("#bed-capacity-range");
				$slider.slider("values", 0, 0);
				$slider.slider("values", 1, 0);
				$('#search_frm')[0].reset();
				$( this ).dialog( "close" );
			}
		}
	});
};

$.fn.GO_VIEW = function (){
	var key_id = $(this).attr('key_id');
	$( "#dialog-view_section" ).dialog({
		open: function( event, ui ) {
			$("div.ui-dialog-titlebar").hide();
			getViewData(key_id);
        },
        modal: true,
		width: 700,
		height:$(document).height(),
		buttons: {
			'close': function(e) {
				$(".spn_text").empty();
				$( this ).dialog( "close" );
			}
		}
	});
};

$.fn.GO_UPDATE = function (){
	var action_goto = $(this).attr('action_goto');
	var key_id = $(this).attr('key_id');
	$("#hidden_product_code").val(key_id);
	$("#action_to_update").val(action_goto);
	$( "#dialog-data_section" ).dialog({
		open: function( event, ui ) {
			$("div.ui-dialog-titlebar").hide();
			if(action_goto == 'EDIT'){
				getEditData(key_id);
			}
			setSliderIns(0,0);
			setComboboxIns();
			setRadioBoxIns();
        },
        modal: true,
		width: 700,
		height:$(document).height(),
		buttons: {
			'submit': function() {
//				$('#data_section').submit();
				resetUi();
				$('#data_section')[0].reset();
				$( this ).dialog( "close" );
			},
			'cancel': function(e) {
				resetUi();
				$('#data_section')[0].reset();
				$( this ).dialog( "close" );
			}
		}
	});
};

$.fn.GO_DELETE = function(){
	
	var productId = $(this).attr('key_id');
	var action = $("#search_frm").attr('action');
	$( "#dialog-message-confirm_delete" ).dialog({
		modal: true,
		buttons: {
			'delete': function() {
				$( this ).dialog( "close" );
				$.ajax({
					 type: "GET",
					 url: action,
					 data: {
						 productId : productId,
						 action : "DELETE"
						 },
					 dataType: "json",
					 success: function(data){
						 if(data[data.length - 1]){
							 loadTable();
						 } else {
							 $("#p_freetext").html('Cannot delete this item!');
							 $( "#dialog-message" ).dialog('open');
						 }
					 },
					error : function(xhr, ajaxOptions, thrownError) {
						$("#p_freetext").html('Error while processing '+xhr+" :: "+thrownError);
						 $( "#dialog-message" ).dialog('open');
					}
				});
			},
			'cancel': function() {
				$( this ).dialog( "close" );
			}
		}
	});
};

$.fn.SEARCH_RESULT = function() {
	loadTable();
};

function setSelectToCombobox(){
	$("#srh_type").combobox();
	$("#srh_department").combobox();
}

function setRadioToSets(){
	$("#div_imp_rate_president").buttonset();
	$("#div_rp_rate_president").buttonset();
	$("#div_imp_rate_director").buttonset();
	$("#div_rp_rate_director").buttonset();
	$("#div_srh_type").buttonset();
}

function setSliderSearch(){
	$( "#bed-capacity-range" ).slider({
	      range: true,
	      min: 0,
	      max: 700,
	      values: [ 0, 0 ],
	      slide: function( event, ui ) {
	    	  $("#srh_bed_min").val(ui.values[ 0 ]);
	    	  $("#srh_bed_max").val(ui.values[ 1 ]);
	      }
	});
	$("#srh_bed_min").val($( "#bed-capacity-range" ).slider( "values", 0 ));
	$("#srh_bed_max").val($( "#bed-capacity-range" ).slider( "values", 1 ));
	$("#srh_bed_min").keyup(function(){
		var regexp = /^[+]?\d+$/;
		if(regexp.test($(this).val())){
			$("#bed-capacity-range").slider("values", 0, $(this).val());
		}
	});
	$("#srh_bed_max").keyup(function(){
		var regexp = /^[+]?\d+$/;
		if(regexp.test($(this).val())){
			$("#bed-capacity-range").slider("values", 1, $(this).val());
		}
	});
}

function setSliderIns(minVal, maxVal){
	$( "#ins_bed-capacity-range" ).slider({
	      range: true,
	      min: 0,
	      max: 700,
	      values: [ parseInt(minVal), parseInt(maxVal) ],
	      slide: function( event, ui ) {
	    	  $("#ins_bed_min").val(ui.values[ 0 ]);
	    	  $("#ins_bed_max").val(ui.values[ 1 ]);
	      }
	});
	$("#ins_bed_min").val($( "#ins_bed-capacity-range" ).slider( "values", 0 ));
	$("#ins_bed_max").val($( "#ins_bed-capacity-range" ).slider( "values", 1 ));
	$("#ins_bed_min").keyup(function(){
		var regexp = /^[+]?\d+$/;
		if(regexp.test($(this).val())){
			$("#ins_bed-capacity-range").slider("values", 0, $(this).val());
		}
	});
	$("#ins_bed_max").keyup(function(){
		var regexp = /^[+]?\d+$/;
		if(regexp.test($(this).val())){
			$("#ins_bed-capacity-range").slider("values", 1, $(this).val());
		}
	});
}

function setComboboxIns(){
	$("#ins_region").combobox({ 
      selected: function (event, ui) { 
    	  getHospitalList($(this).val());
      }
	});
	$("#ins_hospital_name").combobox({ 
      selected: function (event, ui) { 
    	  getHospitalDepartmentList($(this).val());
      }
	});
	$("#ins_hospital_department").combobox();
	$("#ins_bjc_department").combobox({ 
      selected: function (event, ui) { 
    	  getHospitalList($(this).val());
      }
	});
	$("#ins_bjc_category").combobox();
	$("#ins_bjc_brand").combobox();
	$("#ins_bjc_model").combobox();
	
}

function setRadioBoxIns(){
	$("#div_ins_imp_rate_president").buttonset();
	$("#div_ins_rp_rate_president").buttonset();
	$("#div_ins_imp_rate_director").buttonset();
	$("#div_ins_rp_rate_director").buttonset();
	$("#div_ins_type").buttonset();
}

function resetUi(){
	$("#ins_hospital_name").empty();
	$("#ins_hospital_department").empty();
	$("#ins_hospital_name").combobox('destroy');
	$("#ins_hospital_department").combobox('destroy');
	$("#div_ins_imp_rate_president").buttonset('destroy');
	$("#div_ins_imp_rate_president").find(':radio').removeAttr('checked').eq(0).attr('checked', 'checked');
	$("#div_ins_rp_rate_president").buttonset('destroy');
	$("#div_ins_rp_rate_president").find(':radio').removeAttr('checked').eq(0).attr('checked', 'checked');
	$("#div_ins_imp_rate_director").buttonset('destroy');
	$("#div_ins_imp_rate_director").find(':radio').removeAttr('checked').eq(0).attr('checked', 'checked');
	$("#div_ins_rp_rate_director").buttonset('destroy');
	$("#div_ins_rp_rate_director").find(':radio').removeAttr('checked').eq(0).attr('checked', 'checked');
	$("#div_ins_type").buttonset('destroy');
	$("#div_ins_type").find(':radio').removeAttr('checked').eq(0).attr('checked', 'checked');
}

function getHospitalDepartmentList(id){
	$.ajax({
		 type: "GET",
		 url: "CustomerDataManageServlet",
		 data: {
			 id:id,
			 action : "GETHOSPITALDEPARTMENT"
			 },
		 dataType: "json",
		 success: function(data){
			 $("#ins_hospital_department").empty();
			 $("#ins_hospital_department").combobox('destroy');
			 
			 var loop = data.length;
			 var str = "<option value=''>Please select...</option>";
			 for(var i=0; i<loop;i++){
			 	str += "<option value='"+data[i].departmentId+"'>"+data[i].hospitalDepartmentName+"</option>";
			 }
			 
			 $("#ins_hospital_department").html(str);
			 $("#ins_hospital_department").combobox({
				 selected: function (event, ui) { 
				 getHospitalDepartmentDetail($("#ins_hospital_name option:selected").val(), $(this).val());
		     }});
		 },
		error : function(xhr, ajaxOptions, thrownError) {
			alert("Error while processing.");
		}
	});
}

function getHospitalList(regionId){
	$.ajax({
		 type: "GET",
		 url: "CustomerDataManageServlet",
		 data: {
			 id:regionId,
			 action : "GETHOSPITAL"
			 },
		 dataType: "json",
		 success: function(data){
			 $("#ins_hospital_name").empty();
			 $("#ins_hospital_department").empty();
			 $("#ins_hospital_name").combobox('destroy');
			 $("#ins_hospital_department").combobox('destroy');
			 
			 var loop = data.length;
			 var str = "<option value=''>Please select...</option>";
			 for(var i=0; i<loop;i++){
			 	str += "<option value='"+data[i].hospitalCode+"'>"+data[i].hospitalName+"/"+data[i].hospitalNameEn+"</option>";
			 }
			 
			 $("#ins_hospital_name").html(str);
			 $("#ins_hospital_name").combobox({
				 selected: function (event, ui) { 
		    	  getHospitalDepartmentList($(this).val());
		      }});
			 $("#ins_hospital_department").combobox();
		 },
		error : function(xhr, ajaxOptions, thrownError) {
			alert("Error while processing.");
		}
	});
}

function getHospitalDepartmentDetail(hospitalCode, departmentCode){
	$.ajax({
		 type: "GET",
		 url: "CustomerDataManageServlet",
		 data: {
			 hospitalCode:hospitalCode,
			 departmentCode:departmentCode,
			 action : "GETHOSPITALDEPARTMENTDETAIL"
			 },
		 dataType: "json",
		 success: function(data){
			 // tab 1
			 if(data[0].hospitalType == 'PV'){
				 $("#ins_type1").attr('checked','checked');
				 $("#div_ins_type").find('label').eq(0).addClass('ui-state-active');
			 }else if(data[0].hospitalType.trim() == 'PB'){
				 $("#ins_type2").attr('checked','checked');
				 $("#div_ins_type").find('label').eq(1).addClass('ui-state-active');
			 }
			 $("#ins_hospital_address").val(data[0].address);
			 $("#ins_hospital_telephone").val(data[0].telephone);
			 $("#ins_hospital_email").val(data[0].email);
			 setSliderIns(data[0].hospitalDepartment.bedCapMin, data[0].hospitalDepartment.bedCapMax);
			 
			 // tab2
			 $("#ins_president_name").val(data[0].person.title+data[0].person.firstName+" "+data[0].person.lastName);
			 $("#ins_president_telephone").val(data[0].person.telephone);
			 $("#ins_president_email").val(data[0].person.email);
			 $("#ins_imp_rate_president"+data[0].person.impRating.impCode).attr('checked', 'checked');
			 $("#div_ins_imp_rate_president").find('label').removeClass('ui-state-active');
			 $("#div_ins_imp_rate_president").find('label').eq(parseInt(data[0].person.impRating.impCode) - 1).addClass('ui-state-active');
			 $("#ins_rp_rate_president"+data[0].person.rpRating.rpCode).attr('checked', 'checked');
			 $("#div_ins_rp_rate_president").find('label').removeClass('ui-state-active');
			 $("#div_ins_rp_rate_president").find('label').eq(parseInt(data[0].person.rpRating.rpCode) - 1).addClass('ui-state-active');
			 
			 $("#ins_director_name").val(data[0].hospitalDepartment.person.title+data[0].hospitalDepartment.person.firstName+" "+data[0].hospitalDepartment.person.lastName);
			 $("#ins_director_telephone").val(data[0].hospitalDepartment.person.telephone);
			 $("#ins_director_email").val(data[0].hospitalDepartment.person.email);
			 $("#ins_imp_rate_director"+data[0].hospitalDepartment.person.impRating.impCode).attr('checked', 'checked');
			 $("#div_ins_imp_rate_director").find('label').removeClass('ui-state-active');
			 $("#div_ins_imp_rate_director").find('label').eq(parseInt(data[0].hospitalDepartment.person.impRating.impCode) - 1).addClass('ui-state-active');
			 $("#ins_rp_rate_director"+data[0].hospitalDepartment.person.rpRating.rpCode).attr('checked', 'checked');
			 $("#div_ins_rp_rate_director").find('label').removeClass('ui-state-active');
			 $("#div_ins_rp_rate_director").find('label').eq(parseInt(data[0].hospitalDepartment.person.rpRating.rpCode) - 1).addClass('ui-state-active');
		 },
		error : function(xhr, ajaxOptions, thrownError) {
			alert("Error while processing.");
		}
	});
}

function loadTable(){
	var datas = $("#search_frm").serializeArray();
	datas.push({name: 'limitFrom', value: limitFrom});
	datas.push({name: 'limitTo', value: itemPerPage});
	var action = $("#search_frm").attr('action');
	$.ajax({
		 type: "GET",
		 url: action,
		 data: datas,
		 dataType: "json",
		 success: function(data){
			 TableListData = data;
			 var tableLayout = genTable(data, 1);
			 $("#dataTbody").html(tableLayout);
			 $(".act_icon_view").click($.fn.GO_VIEW);
			 $(".act_icon_edit").click($.fn.GO_UPDATE);
			 $(".act_icon_delete").click($.fn.GO_DELETE);
		 },
		error : function(xhr, ajaxOptions, thrownError) {
			alert("Error while processing.");
		}
	});
}

function genTable(data, pages){
	var totalRecords = data.length;
	var maxPage = Math.ceil(totalRecords / itemPerPage);
	var i = 0;
	var loops = totalRecords;
	if(pages > 1){
		i = ((parseInt(pages) * itemPerPage) - itemPerPage);
	}
	if(maxPage > pages){
		loops = i + itemPerPage;
	}
	var tableLayout = "";
	for(; i<loops; i++){
		tableLayout += "<tr id='"+data[i].productCode+"'>" +
						"<td align='center'>" +
						"<img class='act_icon_view' src='images/datamanage/view_x.png' width='20' height='20' key_id='"+data[i].customerDataId+"' action_goto='VIEW'>&nbsp;&nbsp;" +
						//"<img class='act_icon_edit' src='images/datamanage/edit.png' width='20' height='20' key_id='"+data[i].customerDataId+"' action_goto='EDIT'>&nbsp;&nbsp;" +
						//"<img class='act_icon_delete' src='images/datamanage/delete.png' width='20' height='20' key_id='"+data[i].customerDataId+"'></td>" +
						"<td>"+data[i].hospitalNameTh+"/<br>"+data[i].hospitalNameEn+"</td>" +
						"<td>"+data[i].type+"</td>" +
						"<td>"+data[i].hospitalDepartment+"/<br>"+data[i].bedCapacityMin+"-"+data[i].bedCapacityMax+"</td>" +
						"<td>"+data[i].presidentName+"/<br>"+data[i].presidentImpRate+":"+data[i].presidentRpRate+"</td>" +
						"<td>"+data[i].directorName+"/<br>"+data[i].directorImpRate+":"+data[i].directorRpRate+"</td>" +
						"<td>"+data[i].salePerson+"</td>" +
						"</tr>";
	}
	tableLayout += "</tr><tr class='tr_th'><td colspan='10' align='center'>"+	genNumPageList(pages, totalRecords)+"</td>";
	return tableLayout;
}

function genNumPageList(page, totalRecord){
	var numpageLayout = "";
	var totalPage = 1;
	if(totalRecord > itemPerPage){
		totalPage = Math.ceil((totalRecord / itemPerPage)); 
	}
	for(var i=1; i<=totalPage;i++){
		if(i == page){
			numpageLayout += "<b>"+i+"</b>&nbsp;";
		}else{
			numpageLayout += "<span class='spn_numpage' onclick='gotoPage("+i+")'>"+i+"</span>&nbsp;";
		}
	}
	return numpageLayout;
}

function gotoPage(index){
//	var tableLayout = genTable(TableListData, index);
//	$("#dataTbody").html(tableLayout);
	if(index > 1){
		index = index - 1;
	}else {
		index = 0;
	}
	limitFrom = parseInt(index) * itemPerPage;
	var srh_type = $("#srh_type").val();
	var srh_department = $("#srh_department").val();
	var srh_bed_min = $("#srh_bed_min").val();
	var srh_bed_max = $("#srh_bed_max").val();
	var srh_imp_rate_president = $("#srh_imp_rate_president").val();
	var srh_rp_rate_president = $("#srh_rp_rate_president").val();
	var srh_imp_rate_director = $("#srh_imp_rate_director").val();
	var srh_rp_rate_director = $("#srh_rp_rate_director").val();
	loadTable(srh_type, srh_department, srh_bed_min, srh_bed_max, srh_imp_rate_president, srh_rp_rate_president, srh_imp_rate_director, srh_rp_rate_director);
}

function getEditData(key_id){
	var action = $("#search_frm").attr('action');
	$.ajax({
		 type: "GET",
		 url: action,
		 data: {
			 id : key_id,
			 action : "GETEDIT"
			 },
		 dataType: "json",
		 success: function(data){
			 if(data[data.length - 1]){
				 setFieldEdit(data);
			 } else {
				 $("#p_freetext").html('Cannot get item data!');
				 $( "#dialog-message" ).dialog('open');
			 }
		 },
		error : function(xhr, ajaxOptions, thrownError) {
			$("#p_freetext").html('Error while processing '+xhr+" :: "+thrownError);
			 $( "#dialog-message" ).dialog('open');
		}
	});
}

function setFieldEdit(data){
	$("#ins_customerdata_id").val(data[0].customerDataId);
	$("#ins_product_name").val(data[0].productName);
	$("#ins_product_detail").val(data[0].productDetail);
}

function getViewData(key_id){
	var action = $("#search_frm").attr('action');
	$.ajax({
		 type: "GET",
		 url: action,
		 data: {
			 id : key_id,
			 action : "GETVIEW"
			 },
		 dataType: "json",
		 success: function(data){
			 if(data[data.length - 1]){
				 setFieldView(data);
			 } else {
				 $("#p_freetext").html('Cannot get item data!');
				 $( "#dialog-message" ).dialog('open');
			 }
		 },
		error : function(xhr, ajaxOptions, thrownError) {
			$("#p_freetext").html('Error while processing '+xhr+" :: "+thrownError);
			 $( "#dialog-message" ).dialog('open');
		}
	});
}

function setFieldView(data){
	$("#spn_region").html(data[0].region);
	$("#spn_hospital_name").html(data[0].hospitalNameTh+"/"+data[0].hospitalNameEn);
	$("#spn_hospital_department").html(data[0].hospitalDepartment);
	$("#spn_type").html(data[0].type);
	$("#spn_bed").html(data[0].bedCapacityMin+" - "+data[0].bedCapacityMax);
	$("#spn_hospital_address").html(data[0].hospitalAddress);
	$("#spn_hospital_telephone").html(data[0].hospitalTelephone);
	$("#spn_hospital_email").html(data[0].hospitalEmail);
	$("#spn_president_name").html(data[0].presidentName);
	$("#spn_president_telephone").html(data[0].presidentTelephone);
	$("#spn_president_email").html(data[0].presidentEmail);
	$("#spn_imp_rate_president").html(data[0].presidentImpRate);
	$("#spn_rp_rate_president").html(data[0].presidentRpRate);
	$("#spn_director_name").html(data[0].directorName);
	$("#spn_director_telephone").html(data[0].directorTelephone);
	$("#spn_director_email").html(data[0].directorEmail);
	$("#spn_imp_rate_director").html(data[0].directorImpRate);
	$("#spn_rp_rate_director").html(data[0].directorRpRate);
	$("#spn_remark1").html(data[0].remark1);
	$("#spn_bjc_department").html(data[0].bjcDepartment);
	$("#spn_sale_person").html(data[0].salePerson);
	$("#spn_bjc_category").html(data[0].bjcCategory);
	$("#spn_bjc_brand").html(data[0].bjcBrand);
	$("#spn_bjc_model").html(data[0].bjcModel);
	$("#spn_st_competitor").html(data[0].stCompetitor);
	$("#spn_nd_competitor").html(data[0].ndCompetitor);
	$("#spn_rd_competitor").html(data[0].rdCompetitor);
	$("#spn_remark2").html(data[0].remark2);
}